<?php

namespace Encore\Admin\Grid\Filter\Presenter;

use Encore\Admin\Admin;

class DatetimeRange extends Presenter
{
    protected array $id;
    protected string $format;

    public function __construct($format = 'YYYY-MM-DD')
    {
        $this->format = $format;
    }

    protected function prepare()
    {
        $options['format'] = $this->format;
        $options['locale'] = config('app.locale');

        $startOptions = json_encode($options);
        $endOptions = json_encode($options + ['useCurrent' => false]);

        $this->id = [
            'start' => $this->filter->getId() . '_start',
            'end'   => $this->filter->getId() . '_end',
        ];

        $script = <<<EOT
            $('#{$this->id['start']}').datetimepicker($startOptions);
            $('#{$this->id['end']}').datetimepicker($endOptions);
            $("#{$this->id['start']}").on("dp.change", function (e) {
                $('#{$this->id['end']}').data("DateTimePicker").minDate(e.date);
            });
            $("#{$this->id['end']}").on("dp.change", function (e) {
                $('#{$this->id['start']}').data("DateTimePicker").maxDate(e.date);
            });
EOT;

        Admin::script($script);
    }

    public function variables(): array
    {
        $this->prepare();
        return [
            'id'   => $this->id,
        ];
    }
}
